package com.gzu.finalwork.user.service;

import com.gzu.finalwork.user.config.AjaxResult;
import com.gzu.finalwork.entity.user.Users;
import com.gzu.finalwork.user.mapper.UserMapper;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.LocalDateTime;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class UserService {
    
    @Autowired
    private UserMapper userMapper;
    
    // 手机号正则表达式
//    private static final String PHONE_REGEX = "^1[3-9]\\d{9}$";
    
    // 用户注册
    public Object register(Users users,HttpSession session) {
        if (!StringUtils.hasText(users.getUsername())) {
            return AjaxResult.error(-1, "用户名不能为空");
        }
//        if (!StringUtils.hasText(users.getPhone())) {
//            return AjaxResult.error(400, "手机号不能为空");
//        }
        if (!StringUtils.hasText(users.getPassword())) {
            return AjaxResult.error(-1, "密码不能为空");
        }
        // 验证手机号格式
//        if (!Pattern.matches(PHONE_REGEX, users.getPhone())) {
//            return AjaxResult.error(400, "手机号格式不正确");
//        }
        // 验证密码长度
        if (users.getPassword().length() < 6) {
            return AjaxResult.error(-1, "密码长度不能少于6位");
        }
        // 检查手机号是否已注册
//        Integer existingUser = userMapper.selectByPhoneCount(users.getPhone());
//        if (existingUser != null && existingUser > 0) {
//            return AjaxResult.error(400, "该手机号已经被注册");
//        }
        // 创建新用户
        Users newUser = new Users();
        newUser.setUsername(users.getUsername());
//        newUser.setPhone(users.getPhone());
        newUser.setRoles(users.getRoles());
        // 生成盐值并加密密码
        String salt = PasswordUtil.generateSalt();
        String encryptedPassword = PasswordUtil.encryptPassword(users.getPassword(), salt);
        newUser.setSalt(salt);
        newUser.setEmail(users.getEmail());
        newUser.setPassword(encryptedPassword);
        newUser.setStatus(1);
        newUser.setCreatedAt(LocalDateTime.now());
        newUser.setUpdatedAt(LocalDateTime.now());
        // 插入数据库
        int result = userMapper.insertUser(newUser);
        Users user = userMapper.selectByUsername(users.getUsername());
        if(user == null){
            return AjaxResult.error(-1,"找不到用户");
        }else {
            session.setAttribute("userId", user.getUserId());
        }
        if (result > 0) {
            // 返回用户信息（不包含密码和盐值）
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("userId", newUser.getUserId());
            userInfo.put("username", newUser.getUsername());
            userInfo.put("status", newUser.getStatus());
//            userInfo.put("phone", newUser.getPhone());
            return AjaxResult.success("注册成功", userInfo);
        } else {
            return AjaxResult.error(-1, "注册失败，请稍后重试");
        }
    }
    
    // 用户登录
    public Object login(Users users, HttpSession session) {
        // 参数验证
//        if (!StringUtils.hasText(users.getPhone())) {
//            return AjaxResult.error(400, "手机号不能为空");
//        }
        if (!StringUtils.hasText(users.getPassword())) {
            return AjaxResult.error(-401, "密码不能为空");
        }
        // 验证手机号格式
//        if (!Pattern.matches(PHONE_REGEX, users.getPhone())) {
//            return AjaxResult.error(400, "手机号格式不正确");
//        }
        // 根据手机号查询用户
        Users user = userMapper.selectByUsername(users.getUsername());
        if (user == null) {
            return AjaxResult.error(-401, "用户不存在");
        }
        // 验证密码
        boolean passwordValid = PasswordUtil.verifyPassword(
            users.getPassword(),
            user.getPassword(), 
            user.getSalt()
        );
        if(!Objects.equals(users.getRoles(), user.getRoles())){
            return AjaxResult.error(-1, "用户角色不匹配");
        }

        if (!passwordValid) {
            return AjaxResult.error(-401, "密码错误");
        }
        // 检查用户状态
        if (user.getStatus() != 1) {
            return AjaxResult.error(-403, "账户已被禁用，请联系管理员");
        }
        session.setAttribute("userId", user.getUserId());
        return AjaxResult.success("登录成功", user);
    }
    
    //根据用户ID查询用户信息
    public Object getUserInfo(Long userId) {
        if (userId == null) {
            return AjaxResult.error(-1, "用户ID不能为空");
        }
        Users user = userMapper.selectByUserId(userId);
        if (user == null) {
            return AjaxResult.error(-1, "用户不存在");
        }

        return AjaxResult.success(user);
    }

    //删除用户
    public Object deleteUser(Long userId){
        if (userId == null) {
            return AjaxResult.error(-1, "用户ID不能为空");
        }
        int result = userMapper.deleteUser(userId);
        if (result > 0) {
            return AjaxResult.success("删除成功");
        } else {
            return AjaxResult.error(-1, "删除失败，请稍后重试");
        }
    }
    //修改用户密码
    public Object updatePassword(Long userId,String  oldPassword,String  newPassword){
        return 0;
    }



    public class PasswordUtil {
        // 生成随机盐值
        public static String generateSalt() {
            SecureRandom random = new SecureRandom();
            byte[] salt = new byte[16];
            random.nextBytes(salt);
            return Base64.getEncoder().encodeToString(salt);
        }

        // 使用MD5+盐值加密密码
        public static String encryptPassword(String password, String salt) {
            try {
                MessageDigest md = MessageDigest.getInstance("MD5");
                String saltedPassword = password + salt;
                byte[] hashBytes = md.digest(saltedPassword.getBytes());

                StringBuilder sb = new StringBuilder();
                for (byte b : hashBytes) {
                    sb.append(String.format("%02x", b));
                }
                return sb.toString();
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException("密码加密失败", e);
            }
        }

        //验证密码
        public static boolean verifyPassword(String inputPassword, String storedPassword, String salt) {
            String encryptedInput = encryptPassword(inputPassword, salt);
            return encryptedInput.equals(storedPassword);
        }
    }


}
